package com.yiren.manager.ctrl.department;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.Favorites;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrCaregiver;
import com.yiren.entity.YrCaregiverSendOrdersStandard;
import com.yiren.entity.YrCgIndiServiceSendOrder;
import com.yiren.entity.YrCgissSalary;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderArrearage;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrElderWallet;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.department.YrCaregiverForm;
import com.yiren.manager.form.department.YrCgIndiServiceSendOrderForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.form.pension.YrCaregiverSendOrdersStandardForm;
import com.yiren.manager.service.iface.department.YrCaregiverService;
import com.yiren.manager.service.iface.department.YrCgIndiServiceSendOrderService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.pension.YrCaregiverSendOrdersStandardService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("cgIndiServiceSendOrder")
@Controller
public class YrCgIndiServiceSendOrderController
		extends GenericController<YrCgIndiServiceSendOrderForm, YrCgIndiServiceSendOrder> {

	@Autowired
	private YrCgIndiServiceSendOrderService selfService;

	@Autowired
	private YrCaregiverService caregiverService;

	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;

	@Autowired
	private YrElderService elderService;

	@Autowired
	private YrElderWalletService elderWalletService;
	
	@Autowired
	private YrCaregiverSendOrdersStandardService caregiverSendOrdersStandardService;

	// 保存实体 派单
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrCgIndiServiceSendOrderForm> save(String data)
			throws SwallowException, MyException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IntrospectionException {
		HTTPResult<YrCgIndiServiceSendOrderForm> result = new HTTPResult<YrCgIndiServiceSendOrderForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrCgIndiServiceSendOrderForm form = tool.mapper("cgIndiServiceSendOrder",
				YrCgIndiServiceSendOrderForm.class);
		if (null == form) {
			throwExp("param.error");
		}
		String sqlWhere = "elder_id=?1 AND status=0";
		QueryResult<YrCgIndiServiceSendOrder> qrCgIndiServiceSendOrder = selfService
				.find(YrCgIndiServiceSendOrder.class, sqlWhere, new Object[] { form.getElderId() });
		if (qrCgIndiServiceSendOrder.getTotalRecord() > 0) {
			throwExp("派单尚未结束，请勿重复派单");
		}
		if (null == form.getCgIndiServiceSendOrderId() || form.getCgIndiServiceSendOrderId().isEmpty()) {
			form.setCgIndiServiceSendOrderId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
		}
		form.setUpdateTime(new Date());
		YrCgIndiServiceSendOrder entity = ObjectUtils.objectToObject(form, YrCgIndiServiceSendOrder.class);
		selfService.save(entity);

		return result;
	}

	@RequestMapping("findCaregiverDetail")
	@ResponseBody
	public HTTPResult<YrCaregiverForm> findCaregiverDetail(String searchVal) throws MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrCaregiverForm> result = new HTTPResult<YrCaregiverForm>();
		String sqlWhere = "name=?1 OR card_id=?2";
		QueryResult<YrCaregiver> qrCaregiver = caregiverService.find(YrCaregiver.class, sqlWhere,
				new Object[] { searchVal, searchVal });
		if (qrCaregiver.getTotalRecord() < 1) {
			throwExp("查无护理员相关信息");
		}
		YrCaregiver caregiver = qrCaregiver.getResultList().get(0);
		YrCaregiverForm caregiverForm = ObjectUtils.objectToObject(caregiver, YrCaregiverForm.class);

		sqlWhere = "caregiver_id=?1 AND status=0";
		QueryResult<YrCgIndiServiceSendOrder> qr = selfService.find(YrCgIndiServiceSendOrder.class, sqlWhere,
				new Object[] { caregiver.getCaregiverId() });

		List<YrElderBeHospitalForm> elderBeHospitalForms = new ArrayList<YrElderBeHospitalForm>();
		for (YrCgIndiServiceSendOrder entity : qr.getResultList()) {
			String elderId = entity.getElderId();
			sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { elderId });
			if (qrElderBeHospital.getTotalRecord() > 0) {
				YrElderBeHospitalForm elderBeHospital = ObjectUtils.objectToObject(qrElderBeHospital.getResultList().get(0),
				YrElderBeHospitalForm.class);
				YrElder elder = elderService.findOne(elderId);
				if (null != elder) {
					elderBeHospital.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
				}
				elderBeHospitalForms.add(elderBeHospital);
			}
		}
		caregiverForm.setElderBeHospitalForms(elderBeHospitalForms);
		
		YrCaregiverSendOrdersStandard caregiverSendOrdersStandard = caregiverSendOrdersStandardService.findOne(caregiverForm.getCaregiverSendOrdersStandardId());
		if(null!=caregiverSendOrdersStandard){
			YrCaregiverSendOrdersStandardForm sendOrdersStandardForm = ObjectUtils.objectToObject(caregiverSendOrdersStandard, YrCaregiverSendOrdersStandardForm.class);
			caregiverForm.setCaregiverSendOrdersStandardForm(sendOrdersStandardForm);
		}
		
		List<YrCaregiverForm> formList = new ArrayList<YrCaregiverForm>();
		formList.add(caregiverForm);

		result.setData(formList);

		return result;
	}

	@RequestMapping("findAll")
	@ResponseBody
	public HTTPResult<YrCgIndiServiceSendOrderForm> findAll() throws Exception {
		HTTPResult<YrCgIndiServiceSendOrderForm> result = new HTTPResult<YrCgIndiServiceSendOrderForm>();

		List<YrCgIndiServiceSendOrder> entityList = selfService.findAll();
		List<YrCgIndiServiceSendOrderForm> formList = new ArrayList<YrCgIndiServiceSendOrderForm>();
		for (YrCgIndiServiceSendOrder entity : entityList) {
			YrCgIndiServiceSendOrderForm form = toForm(entity);

			YrCaregiver caregiver = caregiverService.findOne(form.getCaregiverId());
			if (null != caregiver) {
				form.setCaregiverForm(ObjectUtils.objectToObject(caregiver, YrCaregiverForm.class));
			}

			String sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { entity.getElderId() });
			if (qrElderBeHospital.getTotalRecord() > 0) {
				YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
				form.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class));
			}
			formList.add(form);
		}

		result.setData(formList);
		return result;
	}

	@RequestMapping("findBySubjectRoomId")
	@ResponseBody
	public HTTPResult<YrCgIndiServiceSendOrderForm> findBySubjectRoomId(String subjectRoomId) throws Exception {
		HTTPResult<YrCgIndiServiceSendOrderForm> result = new HTTPResult<YrCgIndiServiceSendOrderForm>();
		String sqlWhere = "subject_room_id=?1";
		QueryResult<YrCgIndiServiceSendOrder> qr = selfService.find(YrCgIndiServiceSendOrder.class, sqlWhere,
				new Object[] { subjectRoomId });

		List<YrCgIndiServiceSendOrder> entityList = qr.getResultList();
		List<YrCgIndiServiceSendOrderForm> formList = new ArrayList<YrCgIndiServiceSendOrderForm>();
		for (YrCgIndiServiceSendOrder entity : entityList) {
			YrCgIndiServiceSendOrderForm form = toForm(entity);

			YrCaregiver caregiver = caregiverService.findOne(form.getCaregiverId());
			if (null != caregiver) {
				form.setCaregiverForm(ObjectUtils.objectToObject(caregiver, YrCaregiverForm.class));
			}

			sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { entity.getElderId() });
			if (qrElderBeHospital.getTotalRecord() > 0) {
				YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
				form.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class));
			}
			formList.add(form);
		}

		result.setData(formList);
		return result;
	}

	/**
	 * 结束服务
	 * 
	 * @param id
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("finish")
	@ResponseBody
	public HTTPResult<YrCgIndiServiceSendOrderForm> finish(String id) throws MyException {
		HTTPResult<YrCgIndiServiceSendOrderForm> result = new HTTPResult<YrCgIndiServiceSendOrderForm>();
		YrCgIndiServiceSendOrder entity = selfService.findOne(id);
		if(null==entity){
			throwExp("该派单不存在");
		}
		if(entity.getStatus()==1){
			throwExp("该派单已结束，请勿重复提交");
		}
		YrElder elder = elderService.findOne(entity.getElderId());
		if (null == elder) {
			throwExp("查询不到被派单的相关老者");
		}
		
		// 扣取派单费用
		String sqlWhereElderWallet = "elder_id=?1";
		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhereElderWallet,
				new Object[] { entity.getElderId() });
		Date date = new Date();
		
		YrElderWallet elderWallet = null;
		YrElderArrearage elderArrearage = null;
//		YrIndiServiceCostRecord indiServiceCostRecord = null;
		YrElderPayRecord elderPayRecord = null;
		
		if (qrElderWallet.getTotalRecord() > 0) {
//			indiServiceCostRecord = new YrIndiServiceCostRecord();
//			indiServiceCostRecord.setIndiServiceCostRecordId(UUIDGenerator.getUUID());
//			indiServiceCostRecord.setElderId(entity.getElderId());
//			indiServiceCostRecord.setElderName(entity.getElderName());
//			indiServiceCostRecord.setCostStatus(1);
//
//			if(null!=elder){
//				indiServiceCostRecord.setElderCardId(elder.getCardId());
//			}
//			indiServiceCostRecord.setCostMoney(entity.getIndiServicePrice());
//			indiServiceCostRecord.setCostDate(new Date());
		    elderWallet = qrElderWallet.getResultList().get(0);
//			Float money;
			String sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,sqlWhere, new Object[]{elder.getElderId()});
			if(qrElderBeHospital.getTotalRecord()==0){
				throwExp("查询不到老者入院登记信息");
			}
			YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
			if (elderWallet.getWalletBalance() - entity.getIndiServicePrice() >= 0) {
//				money = entity.getIndiServicePrice();
				elderPayRecord = new YrElderPayRecord();
				elderPayRecord.setElderPayRecordId(UUIDGenerator.getUUID());
				elderPayRecord.setCostDesc(entity.getIndiServiceName() + " "
						+ entity.getIndiServicePrice()+"元");
				elderPayRecord.setElderCardId(elder.getCardId());
				elderPayRecord.setPayDate(new Date());
				elderPayRecord.setElderId(entity.getElderId());
				elderPayRecord.setElderName(elder.getName());
				elderPayRecord.setPayStatus(1);
				elderPayRecord.setPayWay(1);
				elderPayRecord.setCostType(3);
				elderPayRecord.setCreateTime(new Date());
				elderPayRecord.setRelationId(entity.getCgIndiServiceSendOrderId());
				// 钱包余额充足
				elderWallet.setWalletBalance(elderWallet.getWalletBalance() - entity.getIndiServicePrice());
				elderPayRecord.setPayMoney(entity.getIndiServicePrice());
				elderPayRecord.setSubjectRoomId(elderBeHospital.getSubjectRoomId());
//				indiServiceCostRecord.setCostMoney(entity.getIndiServicePrice());
			} else {// 余额不足，增加一条欠费记录
//				elderWallet.setWalletBalance(Float.valueOf(0));//扣光钱包剩下的钱
//				elderPayRecord.setPayMoney(elderWallet.getWalletBalance());
//				money = elderWallet.getWalletBalance() - entity.getIndiServicePrice();
				elderArrearage = new YrElderArrearage();
				elderArrearage.setElderArrearageId(UUIDGenerator.getUUID());
				elderArrearage.setSubjectRoomId(elderBeHospital.getSubjectRoomId());
				elderArrearage.setArrearageMoney(entity.getIndiServicePrice());
				elderArrearage.setArrearageReason("钱包余额不足");
				elderArrearage.setArrearageType(3);//设置欠费类型为个性服务费
				elderArrearage.setElderId(entity.getElderId());
				elderArrearage.setElderName(entity.getElderName());
				if (null != elder) {
					elderArrearage.setElderCardId(elder.getCardId());
				}
				elderArrearage.setShouldPayDate(date);
				elderArrearage.setStatus(0);
				elderArrearage.setCreateTime(date);
				elderArrearage.setRelationId(entity.getCgIndiServiceSendOrderId());
				elderArrearage.setArrearagePayWay(-1);
			}
		}else{
			throwExp("该老者尚未有钱包，扣费失败");
		}
		
		entity.setStatus(1);//设置为已完成
		
		//生成该护理员一条个性服务工资记录
		YrCgissSalary cgissSalary = new YrCgissSalary();
		cgissSalary.setCgissSalaryId(UUIDGenerator.getUUID());
		cgissSalary.setCaregiverId(entity.getCaregiverId());
		cgissSalary.setCaregiverName(entity.getCaregiverName());
		cgissSalary.setSalary(entity.getIndiServicePrice());
		cgissSalary.setGrantStatus(0);
		cgissSalary.setSubjectRoomId(entity.getSubjectRoomId());
		cgissSalary.setHandleId("-1");
		cgissSalary.setCreateId("-1");
		cgissSalary.setCreateTime(date);
		cgissSalary.setUpdateTime(date);
		cgissSalary.setDate(date);
		cgissSalary.setIndiServiceName(entity.getIndiServiceName());
		
		Favorites favorites = new Favorites();
		favorites.putFavorite(YrCgIndiServiceSendOrder.class, entity);
		favorites.putFavorite(YrElderWallet.class, elderWallet);
//		favorites.putFavorite(YrIndiServiceCostRecord.class,indiServiceCostRecord);
		favorites.putFavorite(YrElderArrearage.class, elderArrearage);
		favorites.putFavorite(YrElderPayRecord.class, elderPayRecord);
		favorites.putFavorite(YrCgissSalary.class, cgissSalary);
		selfService.executefinish(favorites);
		return result;
	}

//	@RequestMapping("finishBatch")
//	@ResponseBody
//	public HTTPResult<YrCgIndiServiceSendOrderForm> finishBatch(String data) throws MyException, SwallowException {
//		HTTPResult<YrCgIndiServiceSendOrderForm> result = new HTTPResult<YrCgIndiServiceSendOrderForm>();
//		JsonMapperTool tool = new JsonMapperTool(data);
//		String[] ids = tool.mapper("ids", String[].class);
//		if (null == ids) {
//			throwExp("param.error");
//		}
//		for (String id : ids) {
//			YrCgIndiServiceSendOrder entity = selfService.findOne(id);
//			entity.setStatus(1);
//			selfService.save(entity);
//		}
//		return result;
//	}

	@Override
	public YrCgIndiServiceSendOrderForm toForm(YrCgIndiServiceSendOrder e) throws Exception {
		YrCgIndiServiceSendOrderForm form = ObjectUtils.objectToObject(e, YrCgIndiServiceSendOrderForm.class);
		return form;
	}

	@Override
	public YrCgIndiServiceSendOrder toEntity(YrCgIndiServiceSendOrderForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
